package com.ruitu.mall_98_seller.ui.book;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.arad.util.UIUtils;
import com.ruitu.mall_98_seller.R;
import com.ruitu.mall_98_seller.dao.bean.Address;
import com.ruitu.mall_98_seller.dao.bean.Book;
import com.ruitu.mall_98_seller.dao.impl.TextWaterImpl;
import com.ruitu.mall_98_seller.mvp.model.BookModel;
import com.ruitu.mall_98_seller.mvp.presenter.BookPresenter;
import com.ruitu.mall_98_seller.support.util.Util;
import com.ruitu.mall_98_seller.support.util.ViewUtil;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.util.AlertUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import static com.ruitu.mall_98_seller.mvp.presenter.OrderPresenter.TIME_PATTERN;

// 预订单审核页面
public class BookApproveActivity extends BaseActivity<BookPresenter.BookApproveP, BookModel.BookApproveM> {
    // 姓名,联系方式,商品名称,型号,数量,申请时间,收货地址,商品描述
    private TextView tv_name, tv_phone, tv_pro_name, tv_spec, tv_pro_num, tv_time, tv_addr, tv_info;
    private TextView tv_ok, tv_deny, tv_cancel;// 同意,拒绝,取消

    private Book book;// 传过来的预订对象

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_book_appove;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tv_name = findViewById(R.id.tv_name);
        tv_phone = findViewById(R.id.tv_phone);
        tv_pro_name = findViewById(R.id.tv_pro_name);
        tv_spec = findViewById(R.id.tv_spec);
        tv_pro_num = findViewById(R.id.tv_pro_num);
        tv_time = findViewById(R.id.tv_time);
        tv_addr = findViewById(R.id.tv_addr);
        tv_info = findViewById(R.id.tv_info);
        tv_ok = findViewById(R.id.tv_ok);
        tv_deny = findViewById(R.id.tv_deny);
        tv_cancel = findViewById(R.id.tv_cancel);

        setHeadTitle("预订单审批");
        alertDialog = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        setOnClickListener(tv_ok, tv_deny, tv_cancel);

        book = (Book) getIntent().getExtras().getSerializable("book");
        rxList.add(p.reqBookDetail(book.getId()));
        showProgress();
    }

    @Override
    public void onReqComplete(int code, boolean isOk, Object data) {
        if (code == 1) {// 预订单详情
            book = (Book) data;
            if (null != book) {
                setData2View();
            }
        }
        if (code == 2) {// 拒绝
            onOperateSuccess((String) data);
        }
        if (code == 3) {// 同意
            onOperateSuccess((String) data);
        }
    }

    private void setData2View() {
        tv_name.setText(book.getUserName());
        tv_phone.setText(book.getUserPhone());
        tv_pro_name.setText(book.getGoodName());
        tv_spec.setText(book.getGoodsSpec());
        tv_pro_num.setText(book.getGoodsNum());
        tv_time.setText(null == book.getCreateTime() ? "" : new SimpleDateFormat(TIME_PATTERN).format(book.getCreateTime()));
        tv_info.setText(TextUtils.isEmpty(book.getIntro()) ? "用户未填写" : book.getIntro());

        Address addr = book.getAddress();
        tv_addr.setText(addr.getProvince() + addr.getCity() + addr.getCounty() + addr.getAddress());
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_ok) {
            if (null == book.getAddress()) {// 还没请求完成 此时其实也是可以正常审核的

            }
            showDialog();
        }
        if (v == tv_deny) {
            UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", "是否拒绝此预订单？"
                    , "确定", "取消"
                    , new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            p.reqDenyBook(book.getId());
                            showProgressWithText(true, "审批中");
                        }
                    }, null);
        }
        if (v == tv_cancel) {
            finish();
        }
    }

    private AlertDialog alertDialog;
    private View alert_view;// 对话框的布局
    private long selectMillis;// 用户选择的时间的毫秒值

    // 弹窗
    private void showDialog() {
        alert_view = View.inflate(this, R.layout.alert_book_info, null);
        alertDialog.show();
        AlertUtil.setAlertCenterStyle(alertDialog.getWindow(), alert_view, this);

        final TextView tv_time = alert_view.findViewById(R.id.tv_time);
        final EditText et_ratio = alert_view.findViewById(R.id.et_ratio);
        final EditText et_price = alert_view.findViewById(R.id.et_price);
        TextView tv_ok = alert_view.findViewById(R.id.tv_ok);
        TextView tv_cancel = alert_view.findViewById(R.id.tv_cancel);

        et_ratio.addTextChangedListener(new TextWaterImpl() {
            @Override
            public void afterTextChanged(Editable s) {
                double ratio;
                try {
                    ratio = Double.parseDouble(ViewUtil.getTvTxt(et_ratio));
                } catch (Exception e) {
                    ratio = 0.01;
                }
                if (ratio <= 0) {
                    ratio = 0.01;
                    et_ratio.setText(ratio + "");
                    ToastUtils.showShortSafe("预付比例必须是0到100");
                }
                if (ratio > 100) {
                    ratio = 100;
                    et_ratio.setText(ratio + "");
                    ToastUtils.showShortSafe("预付比例必须是0到100");
                }
            }
        });
        et_price.addTextChangedListener(new TextWaterImpl() {
            @Override
            public void afterTextChanged(Editable s) {
                double price;
                try {
                    price = Double.parseDouble(ViewUtil.getTvTxt(et_price));
                } catch (Exception e) {
                    price = 1;
                }
                if (price <= 0) {
                    price = 1;
                    et_price.setText(price + "");
                    ToastUtils.showShortSafe("价格必须大于0");
                }
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        tv_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar ca = Calendar.getInstance();
                int mYear = ca.get(Calendar.YEAR);
                int mMonth = ca.get(Calendar.MONTH);
                int mDay = ca.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog datePickerDialog = new DatePickerDialog(BookApproveActivity.this
                        , new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String y = year + "";
                        String m = Util.add0If1(month + 1);
                        String d = Util.add0If1(dayOfMonth);

                        try {
                            selectMillis = new SimpleDateFormat(TIME_PATTERN).parse(y + "-" + m + "-" + d + " 00:00:00").getTime();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        tv_time.setText(y + "年" + m + "月" + d + "日");
                    }
                }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ViewUtil.isTvEmpty(et_ratio)) {
                    ToastUtils.showShortSafe("请输入预付比例");
                    return;
                }
                if (ViewUtil.isTvEmpty(et_price)) {
                    ToastUtils.showShortSafe("请输入商品单价");
                    return;
                }
                if (ViewUtil.isTvEmpty(tv_time)) {
                    ToastUtils.showShortSafe("请选择发货时间");
                    return;
                }
                alertDialog.dismiss();
                showProgressWithText(true, "审批中");
                p.reqAgreeBook(book.getId(), ViewUtil.getTvTxt(et_ratio), selectMillis + "", ViewUtil.getTvTxt(et_price));
            }
        });

        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        alertDialog.setCanceledOnTouchOutside(false);
    }

    // 操作成功后的弹窗提示信息
    private void onOperateSuccess(String msg) {
        UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", msg
                , "好的", "知道了"
                , new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Arad.bus.post(new EventModel(19083051));// 刷新列表
                        finish();
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Arad.bus.post(new EventModel(19083051));// 刷新列表
                        finish();
                    }
                });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }
}
